<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
	<meta http-equiv=Content-Type content="text/html;charset=utf-8">
	<title>Ads egnine</title>
</head>
<body>
<?php
stage("start");
echo "<pre>";
$DB = Mysql::getInstance();
$SP = new SphinxClient;
$SP->setServer("localhost", 9312);
$SP->setMatchMode(SPH_MATCH_ALL);
$SP->SetArrayResult(true);
$SP->setLimits(0, 1);

$selected = "bmw красный";
echo "Выбранно: ".$selected."\n=========================\n";
$indexes = array();
foreach ($DB->getAll("SELECT `value` FROM `city`") as $item) {
	$item = mb_strtolower($item["value"], "UTF-8");
	$index = $SP->addQuery($selected." ".$item);
	if ($index) {
		$indexes[$item] = $index;
	}

	if (count($indexes) == 31) {
		$r = $SP->runQueries();
		//print_r($r);
		foreach ($indexes as $item => $index) {
			echo $item.": ".$r[$index]["total_found"]."\n";
		}
		$indexes = array();
	}
}
echo "Error: ".$SP->getLastError();

final_stage();
exit;
	stage("Class inits");

	$Logger = Logger::getInstance(LOGS_DIR."/ad_list.log");
	$T = new Templater("tortilla", "stub");
	$Cache = DataCache::getInstance();
	$DB = Mysql::getInstance();
	$Links = Links::getInstance();
	$Drills = Drills::getInstance();

	/// ======================================================================================
	/// Fetching drills

	stage("Selected drills");

	/// At first, drills which was selected

	$where_clause = "";
	$selected_keys = "_s";
	$selected_drills = array();
	foreach ($G["r_info"]["selected"] as $drill_name => $drill_value) {

		$selected_keys .= $drill_name."=".$drill_value;

		if (!empty($where_clause))
			$where_clause .= "\n\t\t\t\t\t\tAND ";
		$where_clause .= "`ads`.`".$G["ad_drills"][$drill_name]["param_field_name"]."` = (SELECT `id` FROM `".$G["ad_drills"][$drill_name]["table_name"]."` WHERE `value` = \"".$DB->escape($drill_value)."\")";

		$cached = false;
		$memcached_key = "drill_".$drill_name.$selected_keys;


		// checking memcache
		if (($cache = $Cache->Get($memcached_key)) !== false) {
			if (!empty($cache) && is_array($cache)) {
				$drill = $cache;
				$cached = true;
			}
		}

		if (!$cached) {
			$query = "
				SELECT
					*
				FROM
					`".$G["ad_drills"][$drill_name]["table_name"]."` as `drill_table`
				WHERE
					`drill_table`.`value` = \"".$DB->escape($drill_value)."\"
			";

			$res = $DB->Query($query);
			$row = $res->FetchRow();

			if (!empty($row)) {
				$drill = array(
					"title" => $drill_name,
					"value" => trim($row["value"]),
					"undo_link" => $Links->compileLink("remove", array($drill_name => $drill_value))
				);
			}

			$Cache->Set($memcached_key, $drill, $G["site_conf"]["ads_list_cache_time"]);
		}

		array_push($selected_drills, $drill);
	}


	/// At second, drills which was not selected

	stage("Not selected drills");

	$drills = array();
	foreach ($ad_drill_display_order as $drill_name) {
		$drill_descr = $G["ad_drills"][$drill_name];

		if (array_key_exists($drill_name, $G["r_info"]["selected"])) continue;

		$limit = $G["site_conf"]["drills_limit"];

		$cached = false;
		$memcached_key = "drill_".$drill_name.$selected_keys."_l".$limit;

		// checking memcache
		if (($cache = $Cache->Get($memcached_key)) !== false) {
			if (!empty($cache) && is_array($cache)) {
				$drill = $cache;
				$cached = true;
			}
		}

		if (!$cached) {

			$variant = 1; // use group by in ads
			$variant = 2; // use drill hashes

			if ($variant === 1) {
				if (empty($G["r_info"]["selected"])) {
					/// No one drill was selected - so SQL is quite simple
					$query = "
						SELECT SQL_NO_CACHE
							*
						FROM
							`".$drill_descr["table_name"]."` as `drill_table`
						ORDER BY
							`drill_table`.`amount` DESC
						LIMIT ".$limit."
					";
				} else {

					/// Drills was selected - so SQL is little complicated

					$query = "
						SELECT SQL_NO_CACHE
							`derived`.*,
							`drill_table`.`value` as `value`
						FROM ( SELECT
								`ads`.`".$drill_descr["param_field_name"]."` as `drill_id`,
								COUNT(*) as `amount`
							FROM
								`ads` as `ads` USE KEY (PRIMARY)
							WHERE
								".$where_clause."
							GROUP BY
								`ads`.`".$drill_descr["param_field_name"]."`
							ORDER BY
								`amount` DESC
							LIMIT ".$limit."
							) as `derived`
						INNER JOIN
							`".$drill_descr["table_name"]."` as `drill_table`
						ON
							`drill_table`.`id` = `derived`.`drill_id`
					";

				}

				$res = $DB->Query($query);

				$drill = array(
					"name" => $drill_name,
					"title" => $drill_name,
					"items" => array()
				);
				while ($row = $res->FetchRow()) {
					$item = array(
						"value" => trim($row["value"]),
						"amount" => $row["amount"],
						"link" => $Links->compileLink("add", array($drill_name => $row["value"]))
					);
					array_push($drill["items"], $item);
				}
			}

			if ($variant === 2) {

				if (empty($G["r_info"]["selected"])) {
					/// No one drill was selected - so SQL is quite simple
					$query = "
						SELECT SQL_NO_CACHE
							*
						FROM
							`".$drill_descr["table_name"]."` as `drill_table`
						ORDER BY
							`drill_table`.`amount` DESC
						LIMIT ".$limit."
					";
					$res = $DB->Query($query);

					$drill = array(
						"name" => $drill_name,
						"title" => $drill_name,
						"items" => array()
					);
					while ($row = $res->FetchRow()) {
						$item = array(
							"value" => trim($row["value"]),
							"amount" => $row["amount"],
							"link" => $Links->compileLink("add", array($drill_name => $row["value"]))
						);
						array_push($drill["items"], $item);
					}
				} else {
					/// Drills was selected - so SQL becomes much more complicates

					$query_with_limit = "
						SELECT SQL_NO_CACHE
							*
						FROM
							`".$drill_descr["table_name"]."` as `drill_table`
						ORDER BY
							`drill_table`.`amount` DESC
						LIMIT ".$limit."
					";

					$correct_query = "
						SELECT SQL_NO_CACHE
							*
						FROM
							`".$drill_descr["table_name"]."` as `drill_table`
					";
					$query = $correct_query;
					//$query = $query_with_limit;

					$res = $DB->Query($query);

					$drill_strings = array();
					$drill_string_to_value = array();

					while ($drill = $res->FetchRow()) {
						$drill_strings[$drill["id"]] = $drill_name."=".$drill["value"];
						$drill_string_to_value[$drill_name."=".$drill["value"]] = $drill["value"];
					}

					$drill_amounts = $Drills->getDrillHashesValue($drill_strings);

					$drill_values = array();
					foreach ($drill_strings as $drill_id => $drill_string) {
						$drill_values[$drill_string_to_value[$drill_string]] = $drill_amounts[$drill_string];
					}
					arsort($drill_values);

					$drill = array(
						"name" => $drill_name,
						"title" => $drill_name,
						"items" => array()
					);
					$i = 0;
					foreach ($drill_values as $drill_value => $drill_amount) {
						$item = array(
							"value" => trim($drill_value),
							"amount" => $drill_amount,
							"link" => $Links->compileLink("add", array($drill_name => $drill_value))
						);
						array_push($drill["items"], $item);

						if ($i++ > $limit)
							break;
					}
				}
			}

			$Cache->Set($memcached_key, $drill, $G["site_conf"]["ads_list_cache_time"]);
		}

		if (count($drill["items"]) > 1) {
			array_push($drills, $drill);
		}
	}


	$T->Assign("drills", $drills);
	$T->Assign("selected_drills", $selected_drills);

	/// ======================================================================================
	/// Fetching ads

	stage("Ads list");

	$ads = array();
	$cached = false;
	$limit = $G["site_conf"]["ads_per_page"];
	$memcached_key = "first_".$limit."_ads";

	// checking memcache
	if (!$cached && ($cache = $Cache->Get($memcached_key)) !== false) {
		if (!empty($cache) && is_array($cache)) {
			$drill = $cache;
			$cached = true;
		}
	}

	if (!$cached) {
		$query = "
			SELECT
				`ads`.*
			FROM
				`ads` USE KEY (PRIMARY)
			".(empty($where_clause)?"":"WHERE ".$where_clause)."
			ORDER BY
				`ads`.`id` DESC
			LIMIT 0, ".$limit."
		";
		$res = $DB->Query($query);
		while ($ad = $res->FetchRow()) {
			array_push($ads, $ad);
		}

		if (!empty($ads)) {
			$distinct_drills = array();
			/// every ad is identical, so we'll take first ad
			foreach ($ads[0] as $drill_name => $drill_id) {
				if (!in_array($drill_name, $distinct_drills))
					array_push($distinct_drills, $drill_name);
			}

			/// walk through each drill, and selects appropriative values for ids
			$drill_ids = array();
			foreach ($distinct_drills as $drill_name) {
				if (!array_key_exists($drill_name, $G["ad_drills"])) {
					continue;
				}
				$drill_ids[$drill_name] = array();

				$ids_to_lookup = array();
				foreach ($ads as $ad_id => $ad_info) {
					if ($ad_info[$drill_name] !== null) {
						array_push($ids_to_lookup, $ad_info[$drill_name]);
					}
				}
				$ids_to_lookup = implode(",", array_unique($ids_to_lookup));

				if (empty($ids_to_lookup)) {
					/// nothing to fetch from database - it means that this drill is not used in any ad
					foreach ($ads as $ad_id => $ad_info) {
						$ads[$ad_id][$drill_name] = "";
					}
					continue;
				}

				$query = "
					SELECT
						`id`,
						`value`
					FROM
						`".$G["ad_drills"][$drill_name]["table_name"]."` as `drill`
					WHERE
						`drill`.`id` IN (".$ids_to_lookup.")
				";
				$res = $DB->Query($query);
				while ($drill_info = $res->FetchRow()) {
					$drill_ids[$drill_name][$drill_info["id"]] = $drill_info["value"];
				}

				foreach ($ads as $ad_id => $ad_info) {
					if (array_key_exists($ad_info[$drill_name], $drill_ids[$drill_name])) {
						$ads[$ad_id][$drill_name] = $drill_ids[$drill_name][$ad_info[$drill_name]];
					} else {
						$ads[$ad_id][$drill_name] = "";
					}
				}
			}
		}

		$Cache->Set($memcached_key, $ads, $G["site_conf"]["ads_list_cache_time"]);
	}
	//echo "<pre>".print_r($ads, 1);exit;
	$T->Assign("ads", $ads);


	/// ======================================================================================
	/// Rendering HTML code

	stage("HTML Rendered");

	/// Language definitions

	if (isset($_GET["lang"]))
		$CURRENT_LANG = $_GET["lang"];
	else
		$CURRENT_LANG = DEFAULT_LANG;

	include(LANGS_DIR."/define.php");
	include(LANGS_DIR."/".$LANG_ASSOC[$CURRENT_LANG]);
	$T->assign("LANG", $LANG);

	/// What template to display

	$T->Display("main_page.html");
?>
